"""
   -*- coding: utf-8 -*-
   @Time    : 2021/3/20 12:28
   @Author  : 狠欢
   @File    : IP_check.py
   @Software: PyCharm
"""
import IPy
import subprocess


def main():
    input_ip = '192.168.0.0/24'
    ip_list_check = get_ip(input_ip)
    check_ip(ip_list_check)


# 获取ip地址
def get_ip(input_ip):
    ip_list = []
    ip = IPy.IP(input_ip)
    for i in ip:
        ip_list.append(str(i))
    # print(ip_list)
    return ip_list


# 判断ip地址是否被占用
def check_ip(ip_list_check):
    for ip in ip_list_check:
        cmd_str = "ping {}".format(ip)
        # 不创建cmd窗口
        DETACHED_PROCESS = 0x00000008
        try:
                subprocess.run(cmd_str, creationflags=DETACHED_PROCESS, timeout=4)
                print(ip, "该ip有人用啦！！！！")
                with open("IP_used.txt", 'a+', encoding='utf-8')as f:
                    f.write(ip)
        except subprocess.TimeoutExpired as e:
            print(ip, "该ip地址没人用！！！！")


if __name__ == '__main__':
    main()


